package com.haiqu.haiqu_helper.service.serviceImpl;

import com.haiqu.haiqu_helper.dao.LicenseBeanRepo;
import com.haiqu.haiqu_helper.model.JsonResult;
import com.haiqu.haiqu_helper.model.requestModel.CheckLicenseParam;
import com.haiqu.haiqu_helper.model.table.LicenseBean;
import com.haiqu.haiqu_helper.service.LicenseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.Optional;

/**
 * className: LicenseServiceImpl
 * description: 证书
 * author: mj
 * date: 2019/9/198:29 PM
 **/
@Service
public class LicenseServiceImpl implements LicenseService {
	@Autowired
	LicenseBeanRepo licenseBeanRepo;
	@Override
	public JsonResult checkLicense(CheckLicenseParam param) {
		JsonResult jsonResult = new JsonResult();
		Optional<LicenseBean> optionalLicenseBean = licenseBeanRepo.findById(param.getFsn());
		if (optionalLicenseBean.isPresent()){
			LicenseBean licenseBean = optionalLicenseBean.get();
			if (licenseBean.getFsession()==null||licenseBean.getFsession().equals("")){
				licenseBean.setFsession(param.getFsession());
				licenseBean.setFregTime(new Date());
				licenseBeanRepo.save(licenseBean);
				jsonResult.setMessage("激活码绑定成功");
				return jsonResult;
			}else{
				if (licenseBean.getFsession().length()==16){
					licenseBean.setFsession(param.getFsession());
					licenseBeanRepo.save(licenseBean);
					jsonResult.setMessage("验证通过");
					return jsonResult;
				}
				if (licenseBean.getFsession().equals(param.getFsession())){
					jsonResult.setMessage("验证通过");
					return jsonResult;
				}else{
					Date time = licenseBean.getFupsessionTime();
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(new Date());
					calendar.add(Calendar.HOUR_OF_DAY, -24);
					/** 更新时间小于 24小时*/
					if (time!=null&&time.getTime()>calendar.getTime().getTime()){
						jsonResult.setCode(JsonResult.STATUS_ERROR);
						jsonResult.setMessage("24小时之后再试");
						return jsonResult;
					}else{
						licenseBean.setFsession(param.getFsession());
						licenseBean.setFupsessionTime(new Date());
						licenseBeanRepo.save(licenseBean);
						jsonResult.setMessage("验证成功");
						return jsonResult;
					}

				}
//				jsonResult.setCode(JsonResult.STATUS_ERROR);
//				jsonResult.setMessage("激活码与设备不匹配");
//				return jsonResult;
			}
		}else{
			jsonResult.setCode(JsonResult.STATUS_ERROR);
			jsonResult.setMessage("激活码不正确");
			return jsonResult;
		}
	}
}
